package com.demo;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * jpsuh 测试类
 *
 * GitHub - jpush/jpush-api-java-client: JiGuang's officially supported Java client library for accessing JPush APIs. 极光官方支持的 Java 版本服务器端 SDK。
 * https://github.com/jpush/jpush-api-java-client
 *
 */
public class JpushUtils {

    //读取配置中的appkey和masterSecret

    private static final Logger LOG = LoggerFactory.getLogger(JpushUtils.class);
    private static final String appKey = "a";
    private static final String masterSecret = "b";

    public static void main(String[] args) {
        JpushUtils.SendPush();
    }

    /**
     * 按别名进行推送
     */
    public static PushResult SendPush() {
        JPushClient jPushClient = new JPushClient(masterSecret, appKey);
        Notification notification = Notification.newBuilder()
                    .addPlatformNotification(AndroidNotification.newBuilder()
                            .setTitle("消息标题")
                            .setAlert("消息内容")
                            .build())
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert("消息内容")
                        .setSound("sound.caf")
                        .build())
                    .build();
        PushPayload push = PushPayload.newBuilder().
                setPlatform(Platform.all())
                .setNotification(notification)
                .setAudience(Audience.alias("")).build();
        PushResult result = null;
        try {
            result = jPushClient.sendPush(push);
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + push.getSendno());
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + push.getSendno());
        }
        if (result == null) {
            LOG.error("与设备通话失败，请联系管理员处理！");
        }
        return result;
    }
}